/*
 * @Author: Wangjun
 * @Date: 2021-06-04 22:01:44
 * @LastEditTime: 2023-12-02 11:13:09
 * @LastEditors: wangjun haodreams@163.com
 * @Description:表格查询
 * @FilePath: \xr_node_calc\controllers\table.go
 * hnxr
 */
package controllers

import (
	"path/filepath"
	"strings"

	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/libs/easy"
	"gitee.com/haodreams/op_node/models"
	"gitee.com/haodreams/report/reportcs"
)

// TableController 表相关的操作
type TableController struct {
	reportcs.TableController
}

func loadResultMap(path string) (mp map[string]string) {
	mp = make(map[string]string)
	lines, err := easy.ReadLines(path+"/detail.csv", true)
	if err != nil {
		return
	}
	for _, line := range lines {
		ss := strings.Split(line, ",")
		if len(ss) < 3 {
			continue
		}
		key := ss[0] + "." + ss[1]
		mp[key] = ss[2]
	}
	return
}

func (m *TableController) data(path string) {
	tableName := filepath.Base(path)
	var items interface{}
	var err error

	switch tableName {
	// case "plants":
	// 	items = models.GetBoss().GetPlantList()
	// case "pvboxs":
	// 	items = models.GetBoss().GetPvBoxList()
	// case "circuits":
	// 	items = models.GetBoss().GetCircuitList()
	// case "inverters":
	// 	items = models.GetBoss().GetInverterList()
	// case "fans":
	// 	items = models.GetBoss().GetFanList()
	case "tasks": //获取任务
	//params := m.GetParam()
	// id, err := params.GetInt("id")
	// if err == nil {
	// 	category := params.GetTrimString("category")
	// 	if category != "" {
	// 		items = models.GetTaskList(id, category)
	// 	}
	// }
	//items = models.GetBoss().GetOPTask()
	case "tasklist":
		items = models.GetBoss().GetOPTask()
	case "dirs":
		//items = models.GetFunctions()
		fi, err := easy.ReadDir("data/data")
		if err != nil {
			m.Error(err.Error())
			return
		}
		idx := 0
		fis := make([]*easy.FileInfo, len(fi))
		for _, d := range fi {
			if d.IsDir {
				fis[idx] = d
				idx++
			}
		}
		items = fis[:idx]
	case "files":
		path := m.GetParam().GetString("path")
		filePath := "data/data/" + path
		fi, err := easy.ReadDir(filePath)
		if err != nil {
			m.Error(err.Error())
			return
		}

		type info struct {
			Name     string
			Code     string
			Time     string
			Category string
			CRC      string
			Result   string
		}
		fis := make([]*info, len(fi))
		idx := 0
		mp := loadResultMap(filePath)
		for _, d := range fi {
			if d.IsDir {
				continue
			}
			ss := strings.Split(d.Name, ".")
			if len(ss) < 5 {
				continue
			}
			fi := new(info)
			fi.Time = ss[0]
			fi.Code = ss[1]
			fi.Category = ss[2]
			fi.Name = ss[3]
			fi.CRC = ss[4]
			fi.Result = mp[ss[0]+"."+ss[1]]
			fis[idx] = fi
			idx++
		}
		items = fis[:idx]
	default:
		path = strings.TrimPrefix(path, "/query")
		tab := m.GetTable("table/" + path)
		if tab == nil {
			return
		}
		tab.Fix()
		m.Dataset(tab)
		return
	}
	if err != nil {
		m.Error(err.Error())
		return
	}

	m.ToWhereSortPage(items, nil)
}

// Query .
func (m *TableController) GetData() {
	uri := m.Request.URL.RequestURI()
	logs.Info(uri)
	path := m.Param("path")
	if m.IsPost() {
		m.data(path)
		return
	}
	//任务要特殊处理的URL
	if m.shortCut(path) {
		return
	}

	m.TableController.GetData()
}

func (m *TableController) shortCut(path string) bool {
	ss := strings.SplitN(path, "/", 3)
	if len(ss) < 3 {
		m.Error("path error")
		return false
	}

	switch ss[len(ss)-1] {
	case "tasks": //这个要单独处理
		table := m.GetValidTable()
		category := m.GetParam().GetTrimString("category")
		id := m.GetParam().GetTrimString("id")
		if table.DataUrl != nil {
			*table.DataUrl += "&category=" + category + "&id=" + id
		}
		if table.UploadUrl != nil {
			*table.UploadUrl += "&category=" + category + "&id=" + id
		}
		if table.DownloadUrl != nil {
			*table.DownloadUrl += "&category=" + category + "&id=" + id
		}
		if table.DeleteUrl != nil {
			*table.DeleteUrl += "&category=" + category + "&id=" + id
		}

		data, err := json.Marshal(table)
		if err != nil {
			logs.Warn(err)
			m.Error(err.Error())
			return true
		}

		m.Header("Content-Type", "application/json; charset=utf-8")
		m.Writer.Write(data)
		return true
	}
	return false
}
